package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"myproject/model"
	"myproject/schemas"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

func taskss(id uint) {
	r := GetRedis()
	orderId := r.ListPop("orderid")
	if orderId != "" {
		// 获取队列中的数据分配给客服
		idInt, _ := strconv.Atoi(orderId)
		// 分配任务
		r.ListAdd(fmt.Sprint(id), idInt)
		fmt.Println("分配任务成功》》》", fmt.Sprint(id), "==", idInt)

		// TODO 调用银行存管平台
		res := CodeOrder()
		fmt.Println(res)

		// TODO 在字典中取出链接，发送消息给客户端
		//SocketSend2(fmt.Sprint(id))

	} else {
		fmt.Println("暂时没有任务---@（^ v ^）R")
	}
}

func AuditTask() {
	// 查询管理员
	var auditlist []model.AdminUser
	model.GetDb().Find(&auditlist, "roleid=1")

	// 分配工作
	for {
		for _, i := range auditlist {
			go taskss(i.ID)
		}
		time.Sleep(time.Second * 10)
	}
}

// 调用银行存管平台
func CodeOrder() int {
	var host = "http://127.0.0.1:5000/codeOrder"
	var param = map[string]string{}

	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
	}
	query := uri.Query()
	for k, v := range param {
		query.Set(k, v)
	}
	uri.RawQuery = query.Encode()

	response, err := http.Get(uri.String())
	if err != nil {
		fmt.Println(err)
	}
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Println(">>", string(result))

	var v interface{}
	_ = json.Unmarshal([]byte(string(result)), &v)
	data := v.(map[string]interface{})
	//fmt.Println(data, "\n", data["code"])
	code, _ := strconv.Atoi(data["code"].(string))

	return code
}

// 标地的更新
func UpdateTarget() {
	fmt.Println("====标地的更新===: ", time.Now().String())
	// 查询标地为超过7天的并且未满标的
	db := model.GetDb()
	sql := "select * from target_land0 where status=2 and money>0 union all select * from target_land1 where status=2 and money>0 union all select * from target_land2 where status=2 and money>0"
	target_all := []model.TargetLand{}
	db.Raw(sql).Scan(&target_all)
	// 循环变里
	for _, i := range target_all {
		if i.AlterDay-1 > 0 {
			// 更新天数
			//code, _ := strconv.Atoi(i.Code)
			//go DayUpdate(code, i.AlterDay)
			fmt.Println("更新天数")
		} else {
			// TODO 更新到期未满标的状态
			go UpdateNotDay(fmt.Sprint(i.Code))
		}

	}

}

// 更新天数
func DayUpdate(code, day int) {
	// 获取表名
	tableName := "target_land" + fmt.Sprint(code%3)
	sql := fmt.Sprintf("update %s set alter_day=? where code=?", tableName)
	model.GetDb().Exec(sql, day-1, code)
	fmt.Println(code, ": 天数已被更新")
}

// 更新到期未满标的状态
func UpdateNotDay(code string) {
	fmt.Println(code, " :已到期")
	// 查询记录
	target_all := []schemas.OrderGet{}
	sql := "select a.target_land, a.bid, a.money, a.status, b.userid, c.name, c.tmoney from targetland_bids as a inner join (select id as bid, userid from bids) as b on a.bid=b.bid inner join (select id,tmoney, name from users) as c on b.userid=c.id where target_land=?"
	model.GetDb().Raw(sql, code).Scan(&target_all)
	fmt.Println(target_all)

	// 对数据进行更新
	for _, i := range target_all {
		go UpdateData(i)
	}
	// 删除缓存
	DelTarget()
}

// 对数据进行更新
func UpdateData(data schemas.OrderGet) {
	// 获取表名
	fmt.Println("data: ", data)
	c, _ := strconv.Atoi(data.TargetLand)
	tableName := "target_land" + fmt.Sprint(c%3)
	fmt.Println("tableName:", tableName)

	// 更新标地表状态（4放款）
	sql := fmt.Sprintf("update %s set status=4 where code=?", tableName)
	model.GetDb().Exec(sql, data.TargetLand)
	//
	// TODO 归还用户余额
	UpdateUserMoney(data)

}

// 归还用户余额
func UpdateUserMoney(data schemas.OrderGet) {
	sql := "update users set tmoney=? where id=?"
	money := int(data.Tmoney) + int(data.Money)
	model.GetDb().Exec(sql, money, data.Userid)

	// 更新账号变更记录表
	bank_info := model.BankChangeRecord{
		Userid:       int(data.Userid),
		Money:        float32(data.Money),
		Tmoney:       float32(data.Tmoney),
		Descriptions: "您投资的项目未满标已到期，已退还。",
	}
	model.GetDb().Create(&bank_info)
	fmt.Println("更新账号变更记录表==》》》")

}

// 删除缓存
func DelTarget() {
	sql := "select * from users"
	user_all := []model.User{}
	model.GetDb().Raw(sql).Scan(&user_all)
	for _, i := range user_all {
		name := "target_" + fmt.Sprint(i.ID)
		GetRedis().StrDel(name)
	}
}

/*
[{42584995692285952 28 200 2 4 王五 58410}]
*/
